package springboot.file.utils;

import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author daiqiang
 * @since 2024/7/12-21:24
 */
@Component
@Slf4j
public class MinioUtils {
    @Resource
    private MinioClient  minioClient;

    @Value("daiqiang")
    private String bucketName;
    @Value("8")
    private Integer expiry;
    private String newFileName(String fileName) {
        // 提取文件扩展名
        String extension = "";
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            extension = fileName.substring(dotIndex);
            fileName = fileName.substring(0, dotIndex);
        }
        // 生成时间戳（使用易于阅读的格式）
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE.ofPattern("yyyyMMdd_HHmmss"));

        // 生成新的文件名：前缀_时间戳_原始文件名.扩展名
        return "upload_" + timestamp + "_" + fileName + extension;

    }


    public Map<String,Object> upload(MultipartFile file) throws  Exception{
        InputStream is = null;
        Map<String,Object> fileResult =new HashMap<>();
        try {
            BucketExistsArgs existsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
            if (!minioClient.bucketExists(existsArgs)) {
                //通不存在，则创建
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(makeBucketArgs);
            }
            is = file.getInputStream();
            String fileName = newFileName(file.getOriginalFilename());
            //文件上传
           minioClient.putObject(PutObjectArgs.builder().object(fileName)
                   .bucket(bucketName)
                   .contentType(file.getContentType())
                   .stream(is, file.getSize(), -1).build());
           is.close();
            fileResult.put("fileName",fileName);
        } catch (Exception e) {
            log.error("上传文件出错", e);
        }
        return fileResult;
    }
    //根据文件名下载文件url
    public String getUrl(String fileName) throws Exception {
        if (fileName.startsWith("http")||fileName.startsWith("/")) {
            return fileName;
        }
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .method(Method.GET)
                    .expiry(expiry, TimeUnit.HOURS)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//   重载  文件加时间
    public String getUrl(String fileName,Integer expiry) throws Exception {
        if (fileName.startsWith("http")||fileName.startsWith("/")) {
            return fileName;
        }
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .method(Method.GET)
                    .expiry(expiry, TimeUnit.HOURS)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //删除文件
    public void delete(String fileName) throws Exception {
        RemoveObjectArgs args=RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .build();
        minioClient.removeObject(args);
    }

}
